package beantoxml;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.StringWriter;

public class BeanToXmlUtil {

    /**
     * 将对象转为对应的xml报文
     *
     * @param object 对象
     * @param classT 类
     * @return xml
     * @throws JAXBException ex
     */
    public static String objectToXml(final Object object, final Class<?>... classT) throws JAXBException {
        final StringWriter writer = new StringWriter();
        final JAXBContext context = JAXBContext.newInstance(classT);
        final Marshaller marshaller = context.createMarshaller();
        //设置编码格式
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);
        marshaller.marshal(object, writer);
        return new String(writer.getBuffer());
    }

}
